/**
 * 在线调试页面js
 * @author 暮光：城中城
 * @since 2018年7月20日
*/

$(document).ready(function(){
	$("#debugRequstType .dropdown-menu li").click(function(){
		var text = $(this).find("a").text();
		$("#debugRequstType .options").text(text);
	});
	/**
	 * 保存参数模板
	 * @returns
	 */
	$(".save-request-template").click(function(){
		Toast.notOpen();
	});
	/**
	 * 发送请求
	 * @returns
	 */
	$(".send-request").click(function(){
		var docUrl = $("#docUrl").text();
		var options = $("#debugRequstType .btn .options").text();
		var postUrl = $("#postUrlInput").val();
		var requestHeaderForm = $("#requestHeaderForm").serializeArray();
		var requestParamForm = $("#requestParamForm").serializeArray();
		var paramBodySend = $("[name=paramBody]").val();
		if(isNotEmpty(paramBodySend)) {
			paramBodySend = JSON.stringify(JSON.parse(paramBodySend));
			saveRequestParamToStore(docUrl, "body", JSON.parse(paramBodySend));
		} else {
			var reqParamStr = "";
			paramBodySend = {};
			for (var i = 0; i < requestParamForm.length; i++) {
				if (requestParamForm[i].name == "paramName" && i < requestParamForm.length) {
					var key = requestParamForm[i].value;
					var value = requestParamForm[i+1].value;
					if(isNotEmpty(key) && isNotEmpty(value)) {
						if(isNotEmpty(reqParamStr)) {
							reqParamStr += "&";
						}
						reqParamStr += key + "=" + value;
						paramBodySend[key] = value;
					}
				}
			}
			postUrl += "?" + reqParamStr;
			saveRequestParamToStore(docUrl, "form", paramBodySend);
			paramBodySend = "";
		}
		$(".send-request .icon").removeClass("hide");
		//console.log(paramBodySend);
		var beforSendTime = new Date().getTime();
		$.ajax({
			url : postUrl,
			sync : false,
			type : options, // 数据发送方式
			dataType : "JSON", // 接受数据格式
			data : paramBodySend,//requestParamForm,
			contentType : "application/x-www-form-urlencoded; charset=UTF-8",
			beforeSend : function(request) {
				var requestHeaderStore = {};
				for (var i = 0; i < requestHeaderForm.length; i++) {
					if (requestHeaderForm[i].name == "paramName" && i < requestHeaderForm.length) {
						var key = requestHeaderForm[i].value;
						var value = requestHeaderForm[i+1].value;
						if(isNotEmpty(key) && isNotEmpty(value)) {
							request.setRequestHeader(key, value);
							requestHeaderStore[key] = value;
						}
					}
				}
				saveRequestParamToStore(docUrl, "header", requestHeaderStore);
			},
			success : function(data, status, xhr) {
			},
			complete : function(xhr) {
				//console.log(xhr);
				$(".send-request .icon").addClass("hide");
				var afterSendTime = new Date().getTime();
				$("#httpRequestStatus").text(xhr.status + "-" + xhr.statusText);
				$("#httpRequestTime").text((afterSendTime - beforSendTime) + "ms");
				if(isEmpty(xhr.responseJSON)) {
					$("#responseBodyTextArea").val(xhr.responseText);
				} else {
					$("#responseBodyTextArea").val(JSON.stringify(xhr.responseJSON, null, 2));
				}
				var allHeaders = xhr.getAllResponseHeaders();
				var headers = allHeaders.split("\r\n");
				$("#tabResponseHeader table tbody").empty();
				for (var i = 0; i < headers.length; i++) {
					if(isEmpty(headers[i])){
						continue;
					}
					var headerArr = headers[i].split(":");
					$("#tabResponseHeader table tbody").append(
						'<tr>'+'<td>'+headerArr[0]+'</td>' + '<td>'+headerArr[1]+'</td>'+'</tr>'
					);
				}
			},
			error : function(data) {
				
			}
		});
	});
	/**
	 * 输入框输入之后，如果是最后一行则在增加一行
	 * @returns
	 */
	$(".param-table").on("keyup", "input[name=paramName]", function(){
		var nextTr = $(this).parents("tr").next();
		if(nextTr.length <= 0) {
			$(this).parents(".param-table").append(getParamTableTr());
		}
	});
	/**
	 * 参数删除一行
	 * @returns
	 */
	$(".param-table").on("click", ".icon-times", function(){
		$(this).parents("tr").remove();
	});
	/**
	 * 在线调试管理
	 */
	$("#onlineDebugLi").click(function(){
		$(".tab-page").hide();
		$(".tab-online-debug-page").show();
		createOnlineDebugParamTable();
	});
	/**
	 * 在线调试管理-刷新
	 */
	$(".tab-online-debug-page .refresh").click(function(){
		createOnlineDebugParamTable();
	});
	/**
	 * 在线调试管理-展开所有
	 */
	$(".tab-online-debug-page .expand-all").click(function(){
		$("#onlineDebugParamTable .option-img").attr("src", "webjars/mg-ui/img/expanded.png")
		$("#onlineDebugParamTable .option-img").parent().next().show();
	});
	/**
	 * 在线调试管理-收起所有
	 */
	$(".tab-online-debug-page .collapse-all").click(function(){
		$("#onlineDebugParamTable .option-img").attr("src", "webjars/mg-ui/img/collapsed.png")
		$("#onlineDebugParamTable .option-img").parent().next().hide();
	});
	/**
	 * 在线调试-删除所有参数
	 */
	$(".tab-online-debug-page").on("click", ".del-all-param", function(){
		$.zui.store.forEach(function(key, value) {// 遍历所有本地存储的条目
			if(!key.startWith('p-request-obj-')) {
				return;
			}
			$.zui.store.remove(key);
		});
		createOnlineDebugParamTable();
	});
	/**
	 * 在线调试-删除参数
	 */
	$(".tab-online-debug-page").on("click", ".del-param", function(){
		var key = $(this).attr("key");
		if(isNotEmpty(key)) {
			$.zui.store.remove(key);
			$(this).parents("tr").remove();
		}
	});
});

/**
 * 生成在线调试管理页面
 * @returns
 */
function createOnlineDebugParamTable() {
	$("#onlineDebugParamTable tbody").empty();
	$.zui.store.forEach(function(key, value) {// 遍历所有本地存储的条目
		if(!key.startWith('p-request-obj-')) {
			return;
		}
		var newKey = key.substring(14, key.length);
		var htmlStr = Formatjson.processObjectToHtmlPre(value, 0, false, false, false);
		$("#onlineDebugParamTable tbody").append(
			'<tr>'
				+'<td>'+newKey+'</td>'
				+'<td>'+htmlStr+'</td>'
				+'<td><button class="btn btn-danger del-param" type="button" key="'+key+'">删除</button></td>'
			+'</tr>'
		);
	});
}

/**
 * 生成在线调试相关数据
 * @param requestParamObj
 * @returns
 */
function createOnlineDebugRequestParam(requestParamObj, url) {
	var pRequestObj = $.zui.store.get('p-request-obj-' + url);
	if(isEmptyObject(pRequestObj)) {
		pRequestObj = {};
	}
	// 清空参数列表
	$("#tabParamHeader table tbody .new").remove();
	$("#tabParamTypeForm table tbody .new").remove();
	$("#tabResponseHeader table tbody").empty();
	$("#tabParamHeader .form-control").val("");
	$("#tabParamTypeForm .form-control").val("");
	$("#responseBodyTextArea").val("");
	var onlyUseLastParam = (userSettings.onlyUseLastParam == 1);
	var onlyUseLastHeader = onlyUseLastParam && !isEmptyObject(pRequestObj.header);
	var onlyUseLastForm = onlyUseLastParam && !isEmptyObject(pRequestObj.form);
	var onlyUseLastBody = onlyUseLastParam && !isEmptyObject(pRequestObj.body);
	var headerValueCount = 0, formValueCount = 0;
	Object.keys(requestParamObj).forEach(function(key){
		var tempParam = requestParamObj[key];
		if (key == "p-body-obj") {
			var paramObj = onlyUseLastBody ? {} : getParamBodyTransObj(tempParam);
			var bodyObj = pRequestObj.body;
			if(!isEmptyObject(bodyObj)) {
				paramObj = $.extend(true, paramObj, bodyObj);
			}
			$("#tabParamTypeBody textarea").val(JSON.stringify(paramObj, null, 2));
			$("#tabParamBody .nav li").eq(1).find("a").click();
		} else {
			if (tempParam.paramIn == "header" && !onlyUseLastHeader) {
				var headerVal = "";
				var headerObj = pRequestObj.header;
				if(!isEmptyObject(headerObj) && isNotEmpty(headerObj[key])) {
					headerVal = headerObj[key];
					headerObj[key] = "";// 赋值为空，后面不再使用
				}
				if(headerValueCount > 0) {
					$("#tabParamHeader table tbody").append(getParamTableTr(key, headerVal, "", tempParam.paramDesc));
				} else {
					$("#tabParamHeader table tbody .base input[name=paramName]").val(key);
					$("#tabParamHeader table tbody .base input[name=paramValue]").val(headerVal);
				}
				headerValueCount++;
			} else if (tempParam.paramIn == "query" && !onlyUseLastForm) {
				var formVal = "";
				var formObj = pRequestObj.form;
				if(!isEmptyObject(formObj) && isNotEmpty(formObj[key])) {
					formVal = formObj[key];
					formObj[key] = "";// 赋值为空，后面不再使用
				}
				if(formValueCount > 0) {
					$("#tabParamTypeForm table tbody").append(getParamTableTr(key, formVal, "", tempParam.paramDesc));
				} else {
					$("#tabParamTypeForm table tbody .base input[name=paramName]").val(key);
					$("#tabParamTypeForm table tbody .base input[name=paramValue]").val(formVal);
				}
				$("#tabParamBody .nav li").eq(0).find("a").click();
				formValueCount++;
			}
		}
	});
	// 处理参数外的header
	var headerObj = pRequestObj.header;
	if(!isEmptyObject(headerObj)) {
		Object.keys(headerObj).forEach(function(key){
			if(isNotEmpty(headerObj[key])) {
				if(headerValueCount > 0) {
					$("#tabParamHeader table tbody").append(getParamTableTr(key, headerObj[key], "", ""));
				} else {
					$("#tabParamHeader table tbody .base input[name=paramName]").val(key);
					$("#tabParamHeader table tbody .base input[name=paramValue]").val(headerObj[key]);
				}
				headerValueCount++;
			}
		});
	}
	// 处理参数外的form
	var formObj = pRequestObj.form;
	if(!isEmptyObject(formObj)) {
		Object.keys(formObj).forEach(function(key){
			if(isNotEmpty(formObj[key])) {
				if(formValueCount > 0) {
					$("#tabParamTypeForm table tbody").append(getParamTableTr(key, formObj[key], "", ""));
				} else {
					$("#tabParamTypeForm table tbody .base input[name=paramName]").val(key);
					$("#tabParamTypeForm table tbody .base input[name=paramValue]").val(formObj[key]);
				}
				formValueCount++;
			}
		});
	}
	if(headerValueCount > 0) {
		$("#tabParamHeader table tbody").append(getParamTableTr("", "", "", ""));
	}
	if(formValueCount > 0) {
		$("#tabParamTypeForm table tbody").append(getParamTableTr("", "", "", ""));
	}
}

/**
 * 获取测试的对象
 */
function getParamBodyTransObj(paramObj) {
	var newObject = $.extend(true, {}, paramObj);
	Object.keys(newObject).forEach(function(key){
		var subObj = newObject[key];
		if(typeof subObj == 'object') {
			if (subObj.hasOwnProperty("isParamObj")) {
				newObject[key] = getNotEmptyStr(subObj.value);
			} else if(subObj instanceof Array) {
				subObj[0] = getParamBodyTransObj(subObj[0]);
			} else {
				newObject[key] = getParamBodyTransObj(subObj);
			}
		}
	});
	return newObject;
}

/**
 * 保存请求参数
 * @returns
 */
function saveRequestParamToStore(url, name, value) {
	var pRequestObj = $.zui.store.get('p-request-obj-' + url);
	if(isEmptyObject(pRequestObj)) {
		pRequestObj = {};
	}
	pRequestObj[name] = value;
	$.zui.store.set('p-request-obj-' + url, pRequestObj);
}

/**
 * 获取参数的tr
 * @param name
 * @param value
 * @param namePl
 * @param valuePl
 * @returns
 */
function getParamTableTr(name, value, namePl, valuePl) {
	name = getNotEmptyStr(name, "");
	value = getNotEmptyStr(value, "");
	namePl = getNotEmptyStr(namePl, "");
	valuePl = getNotEmptyStr(valuePl, "");
	var resultStr = 
	'<tr class="new">'
		+'<td><input type="text" class="form-control" name="paramName" value="'+name+'" placeholder="'+namePl+'"></td>'
		+'<td><input type="text" class="form-control" name="paramValue" value="'+value+'" placeholder="'+valuePl+'"></td>'
		+'<td><i class="icon-times"></i></td>'
	+'</tr>';
	return resultStr;
}

